<?php
/**
 * PnmController.php
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 2.0 of the Apache license
 * that is available through the world-wide-web at the following URI:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * @category Controller
 * @package  Controller
 * @author   Alex Kopp <koppa@rpi.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link     http://http://code.google.com/p/tri-chi/
 */

Yii::import('application.vendors.*');
require_once 'SimpleImage.php';

/**
 * PnmController
 *
 * The controller that manages the Pnms in the GLOrganizer system
 *
 * @category Controller
 * @package  Controller
 * @author   Alex Kopp <koppa@rpi.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link     http://http://code.google.com/p/tri-chi/
 */
class PnmController extends Controller
{
    public $layout='//layouts/main';
    
    /**
     * This is the list of filters we would like to enable for this controller.
     * 
     * We want to limit access to this controller... Thus, including 'accessControl'
     * 
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * 
     * Only authenticated members should be permitted log out
     * Everyone is permitted to log in
     * 
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array('index','view','update','admin','create','exportphonenumbers'),
                'roles'=>array('member'),
            ),
            array('allow',
                'actions'=>array('delete', 'emailpnms'),
                'roles'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * View Detailed Information about all the ratings a PNM has received
     * 
     * @param integer $id the id of the PNM to be displayed
     * 
     * @return void
     */
    public function actionViewRatings($id)
    {
        //To be implemented
    }    
    
    /**
     * View Detailed Information about a PNM
     * 
     * @param integer $id the id of the PNM to be displayed
     * 
     * @return void
     */
    public function actionView($id)
    {
        $model = $this->loadModel($id);
        
        if (isset($_POST['ratingsList'])) {
        	$rating = Ratings::model()->find(array(
				'condition'=>'member_username=:member_username AND pnm_id=:pnm_id',
				'params'=>array(':member_username'=>Yii::app()->user->name, ':pnm_id'=>$id),
			));
			if (is_null($rating))
			{
				if ($_POST['ratingsList'] != 0)
				{
					//Create a new rating
					$newRating = new Ratings;
					$newRating->rating = $_POST['ratingsList'];
					$newRating->pnm_id = $id;
					$newRating->member_username = Yii::app()->user->name;
					$newRating->save();
				}
			}
			else
			{
				if ($_POST['ratingsList'] != 0)
				{
					//Update record with new rating
					$rating->rating = $_POST['ratingsList'];
					$rating->save();
				}
				else
				{
					//Delete the record
					$rating->delete();
				}
			}
        }
        $customFieldModel = new Customfields;
        $pnmPictureModel=PnmPictures::model()->findByPk($model->picture_id);
        if ($pnmPictureModel == null) {
            $pnmPictureModel = new PnmPictures();
            $pnmPictureModel->filename = "unknown.jpg";
            $pnmPictureModel->thumbnail_filename = "unknown.thumb.jpg";
        }
        
		//Find the row based on the member_username of the current member and the PNM_id
		$ratingsModel = Ratings::model()->find(array(
			'condition'=>'member_username=:member_username AND pnm_id=:pnm_id',
			'params'=>array(':member_username'=>Yii::app()->user->name, ':pnm_id'=>$id),
		));
		$allRatingsModel = Ratings::model()->findAll('pnm_id=:pnm_id', array(':pnm_id'=>$id));
		$averageRating = 0;
		$numRatings = count($allRatingsModel);
		for ($i = 0; $i < count($allRatingsModel); $i++)
		{
			$averageRating += $allRatingsModel[$i]->rating;
		}
		if ($numRatings  > 0)
		{
			$averageRating = $averageRating / $numRatings;
		}
        $dropdown = CHtml::beginForm().CHtml::dropDownList('ratingsList', '', array('0' => 'Clear Rating', '1', '2', '3', '4', '5'),
			array('onchange'=>'this.form.submit()', 'prompt'=>'Choose a Rating')).CHtml::endForm();   

		//Get Events Attended
		$arrEventsAttended = Attendedevent::model()->findAll('pnm_id=:pnm_id', array(':pnm_id'=>$id));
		$cleanEventsAttended = array();
		foreach ($arrEventsAttended as $e) {
		    $cleanEventsAttended[$e->event_id] = Events::model()->find("id =:event_id", array(':event_id'=>$e->event_id))->name;
		}
        
		//Introductions		
		$introduction = Introductions::model()->find(array(
				'condition'=>'member_username=:member_username AND pnm_id=:pnm_id',
				'params'=>array(':member_username'=>Yii::app()->user->name, ':pnm_id'=>$id),
			));
		if (isset($_POST['metPNM']))
		{
			if (is_null($introduction))
			{
				$newIntroduction = new Introductions;
				$newIntroduction->pnm_id = $id;
				$newIntroduction->member_username = Yii::app()->user->name;
				$newIntroduction->save();
			}
		}
		if (isset($_POST['notMetPNM']))
		{
			if (!is_null($introduction))
			{
				$introduction->delete();
			}
		}
		
		$introduction = Introductions::model()->find(array(
				'condition'=>'member_username=:member_username AND pnm_id=:pnm_id',
				'params'=>array(':member_username'=>Yii::app()->user->name, ':pnm_id'=>$id),
			));
		if (is_null($introduction))
		{
			//Display "I have met this PNM" button if record does not exist
			$introButton = CHtml::beginForm().CHtml::submitButton('I have met this PNM', array('name'=>'metPNM')).CHtml::endForm();
		}
		else
		{
			//Display "I have not met this PNM" button if record exists
			$introButton = CHtml::beginForm().CHtml::submitButton('I have not met this PNM', array('name'=>'notMetPNM')).CHtml::endForm();
		}
		$introductionsModel = Introductions::model()->findAll('pnm_id=:pnm_id', array(':pnm_id'=>$id));
		$numIntroductions = count($introductionsModel);
		
		
        $this->render(
            'view', array(
                'model'=>$model,
                'pnmPictureModel'=>$pnmPictureModel,
                'customFields'=>$customFieldModel->findAll(array('order'=>'weight')),
        		'ratingsModel'=>$ratingsModel,
				'averageRating'=>$averageRating,
				'numRatings'=>$numRatings,
				'dropdown'=>$dropdown,
                'eventsAttended'=>$cleanEventsAttended,
				'numIntroductions'=>$numIntroductions,
				'introButton'=>$introButton,        
            )
        );
    }

    /**
     * Creates a new PNM.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * 
     * @return void
     */
    public function actionCreate()
    {        
        $model=new Pnm;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Pnm'])) {
            $fileName = "";
            $model->attributes=$_POST['Pnm'];
            if ($model->validate()) {
                if ($model->dorm == '') {
                    $model->dorm = null;
                }
                $CUploadedFileInstance
                    = CUploadedFile::getInstance($model, 'picture_id');
                //Don't forget to save picture_id!

                if (!is_null($CUploadedFileInstance)) {
                    $model->picture_id
                        = CUploadedFile::getInstance($model, 'picture_id');
                } else {
                    $model->picture_id=null;
                }

                if (!is_null($CUploadedFileInstance)) {
                    $fileName
                        = tempnam(Yii::app()->params['userImagesPath'], 'img');
                    $ext = pathinfo($model->picture_id, PATHINFO_EXTENSION);
                    unlink($fileName);
                    $thumbFileName = $fileName . '.thumb.' . $ext;
                    $fileName = $fileName . '.' . $ext;
                    $model->picture_id->saveAs($fileName);

                    //Create Thumbnail
                    $image = new SimpleImage();
                    $image->load($fileName);
                    if ($image->getWidth() > 250) {
                        $image->resizeToWidth(250);
                    }
                    $image->save($thumbFileName);

                     
                    //Time to add row to pnm_pictures
                    $pnmPicturesModel = new PnmPictures;
                    $pnmPicturesModel->filename = basename($fileName);
                    $pnmPicturesModel->thumbnail_filename = basename($thumbFileName);
                    $pnmPicturesModel->save();
                     
                    $model->picture_id=$pnmPicturesModel->id;
                }
                if ($model->save()) {
                    $this->redirect(array('view','id'=>$model->id));
                }

            }
        }
        
        
        $this->render(
            'create', array(
                'model'=>$model,
            )
        );
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id the ID of the model to be updated
     * 
     * @return void
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Pnm'])) {
            $fileName          = "";
            $oldPictureId      = $model->picture_id;
            $model->attributes = $_POST['Pnm'];
            $customFieldData = $_POST['CustomField'];
            if ($model->validate()) {
                if ($model->dorm == '') {
                    $model->dorm = null;
                }
                $CUploadedFileInstance
                    = CUploadedFile::getInstance($model, 'picture_id');


                if (!is_null($CUploadedFileInstance)) { //User uploaded new picture
                    $model->picture_id
                        = CUploadedFile::getInstance($model, 'picture_id');
                    $fileName = tempnam(Yii::app()->params['userImagesPath'], 'img');
                    $ext = pathinfo($model->picture_id, PATHINFO_EXTENSION);
                    unlink($fileName);
                    $thumbFileName = $fileName . '.thumb.' . $ext;
                    $fileName = $fileName . '.' . $ext;
                    $model->picture_id->saveAs($fileName);

                    //Create Thumbnail
                    $image = new SimpleImage();
                    $image->load($fileName);
                    if ($image->getWidth() > 250) {
                        $image->resizeToWidth(250);
                    }
                    $image->save($thumbFileName);

                     
                    //Time to add row to pnm_pictures
                    $pnmPicturesModel = new PnmPictures;
                    $pnmPicturesModel->filename = basename($fileName);
                    $pnmPicturesModel->thumbnail_filename = basename($thumbFileName);
                    $pnmPicturesModel->save();
                     
                    $model->picture_id=$pnmPicturesModel->id;
                } else {
                    if (is_numeric($oldPictureId)) {
                        $model->picture_id=$oldPictureId;
                    } else {
                        $model->picture_id=null;
                    }
                }
                if ($model->save()) {
                    //If PNM has old picture, and we updated it
                    if (is_numeric($oldPictureId)
                        && !is_null($CUploadedFileInstance)
                    ) {
                        $oldPNMPicturesModel
                            = PnmPictures::model()->findByPk($oldPictureId);
                            
                        //Now Delete Images
                        if (($oldPNMPicturesModel->filename != "") && file_exists(Yii::app()->params['userImagesPath'] . $oldPNMPicturesModel->filename)) {
                            unlink(Yii::app()->params['userImagesPath'] . $oldPNMPicturesModel->filename);
                        }
                        if (($oldPNMPicturesModel->thumbnail_filename != "") && file_exists(Yii::app()->params['userImagesPath'] . $oldPNMPicturesModel->thumbnail_filename)) {
                            unlink(Yii::app()->params['userImagesPath'] . $oldPNMPicturesModel->thumbnail_filename);
                        }
                        $oldPNMPicturesModel->delete();
                         
                    }
                    //Now we need to save the custom field information
                    foreach ($customFieldData as $cfid => $cfvalue) {
                        $cifv=Customfieldvalues::model()->find('pnm_id =:pnm_id AND custom_field_id =:cfid', array(':pnm_id'=> $model->id, ':cfid' => $cfid));

                        if (is_null($cifv)) { //If custom information field doesnt exist, create one
                            $mCFV = new Customfieldvalues;
                            $mCFV->pnm_id = $model->id;
                            $mCFV->custom_field_id = $cfid;
                            $mCFV->value = $cfvalue;
                            $mCFV->save();                            
                        } else { //Exists, so update it
                            $cifv->value = $cfvalue;
                            $cifv->save();                            
                        }
                    }
                    $this->redirect(array('view','id'=>$model->id));
                }
            }
        }
        
        $customFieldModel = new Customfields;
        $customFields = $customFieldModel->findAll(array('order'=>'weight'));
        
        $customFieldValues = new Customfieldvalues;
        $cfv = $customFieldValues->findAll('pnm_id =:pnm_id', array(':pnm_id'=> $model->id));

        $this->render(
            'update', array(
                'model'=>$model,
                'customFields' =>$customFields,
                'customFieldValues' =>$cfv,
            )
        );
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * 
     * @param integer $id the ID of the model to be deleted
     * 
     * @return void
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $pnmRow = $this->loadModel($id);
            $pnmPictureRow = PnmPictures::model()->findByPk($pnmRow->picture_id);
            //echo Yii::trace(CVarDumper::dumpAsString($pnmRow),'vardump');
            //echo Yii::trace(CVarDumper::dumpAsString($pnmPictureRow),'vardump');
            if ($pnmPictureRow != null) {
                //Delete Image
                if (($pnmPictureRow->filename != "") && file_exists(Yii::app()->params['userImagesPath'] . $pnmPictureRow->filename)) {
                    unlink(Yii::app()->params['userImagesPath'] . $pnmPictureRow->filename);
                }
                if (($pnmPictureRow->thumbnail_filename != "") && file_exists(Yii::app()->params['userImagesPath'] . $pnmPictureRow->thumbnail_filename)) {
                    unlink(Yii::app()->params['userImagesPath'] . $pnmPictureRow->thumbnail_filename);
                }
            }
            
            //Delete All Custom Field Values
            $customFieldValues = Customfieldvalues::model()->findAll('pnm_id=:pnmid', array(':pnmid'=>$id));
            foreach ($customFieldValues as $cfv) {
                $cfv->delete();
            }
            
            //Delete All Attended Event Values
            $attendedEventValues = Attendedevent::model()->findAll('pnm_id=:pnmid', array(':pnmid'=>$id));
            foreach ($attendedEventValues as $aev) {
                $aev->delete();
            }
            
            //Delete All Rating Values
            $ratePNMValues = Ratings::model()->findAll('pnm_id=:pnmid', array(':pnmid'=>$id));
            foreach ($ratePNMValues as $rpv) {
                $rpv->delete();
            }
            
            //Delete All Introduction Values
            $introductionValues = Introductions::model()->findAll('pnm_id=:pnmid', array(':pnmid'=>$id));
            foreach ($introductionValues as $iv) {
                $iv->delete();
            }
            
            $this->loadModel($id)->delete();
            PnmPictures::model()->deleteByPk($pnmRow->picture_id);
             

            // if AJAX request (triggered by deletion via
            // admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(
                    isset($_POST['returnUrl'])
                    ? $_POST['returnUrl']
                    : array('admin')
                );
            }
        } else {
            throw new CHttpException(
                400, 'Invalid request. Please do not repeat this request again.'
            );
        }
    }

    /**
     * Lists all PNMs
     * 
     * @return void
     */
    public function actionIndex()
    {
        $model=new Pnm('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Pnm'])) {
            $model->attributes=$_GET['Pnm'];
        }

        $newModel=new Pnm;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Pnm'])) {
            $fileName = "";
            $newModel->attributes=$_POST['Pnm'];
            $customFieldData = $_POST['CustomField'];
            //$this->render('test',array('customField' => $customFieldData));
            
            if ($newModel->validate()) {
                if ($newModel->dorm == '') {
                    $newModel->dorm = null;
                }
                $CUploadedFileInstance
                    = CUploadedFile::getInstance($newModel, 'picture_id');
                //Don't forget to save picture_id

                if (!is_null($CUploadedFileInstance)) {
                    $newModel->picture_id
                        = CUploadedFile::getInstance($newModel, 'picture_id');
                } else {
                    $newModel->picture_id=null;
                }

                if (!is_null($CUploadedFileInstance)) {
                    $fileName = tempnam(Yii::app()->params['userImagesPath'], 'img');
                    $ext = pathinfo($newModel->picture_id, PATHINFO_EXTENSION);
                    unlink($fileName);
                    $thumbFileName = $fileName . '.thumb.' . $ext;
                    $fileName = $fileName . '.' . $ext;
                    $newModel->picture_id->saveAs($fileName);

                    //Create Thumbnail
                    $image = new SimpleImage();
                    $image->load($fileName);
                    if ($image->getWidth() > 250) {
                        $image->resizeToWidth(250);
                    }
                    $image->save($thumbFileName);

                     
                    //Time to add row to pnm_pictures
                    $pnmPicturesModel = new PnmPictures;
                    $pnmPicturesModel->filename = basename($fileName);
                    $pnmPicturesModel->thumbnail_filename = basename($thumbFileName);
                    $pnmPicturesModel->save();
                     
                    $newModel->picture_id=$pnmPicturesModel->id;
                }
                if ($newModel->save()) {
                    //Now we need to save the custom field information
                    foreach ($customFieldData as $cfid => $cfvalue) {
                        $mCFV = new Customfieldvalues;
                        $mCFV->pnm_id = $newModel->id;
                        $mCFV->custom_field_id = $cfid;
                        $mCFV->value = $cfvalue;
                        $mCFV->save();
                    }
                    
                    $this->redirect(array('view','id'=>$newModel->id));
                }
                
            }
            
        }

        
        //Start Custom Information Fields
        $customFieldModel = new Customfields;
        $customFields = $customFieldModel->findAll(array('order'=>'weight'));
        
        $this->render(
            'index', array(
                'newModel'=>$newModel,
                'model'=>$model,
                'customFields' =>$customFields,
            )
        );
        
    }
    
    /**
     * Export all PNM phone numbers to CSV
     * 
     * @return void
     */
    
    public function actionExportphonenumbers()
    {
        $model=Pnm::model()->findAll();
        
        $csvData = array();
        array_push($csvData, array('First Name', 'Last Name', 'Phone Number'));
        foreach ($model as $pnm) {
            if (!empty($pnm->phone_number)) {
                array_push($csvData, array($pnm->first_name, $pnm->last_name, $pnm->phone_number));
            }
        }
        
        $file = "GLOrganizerExport.csv";
        $fp = fopen($file, 'w');
        foreach ($csvData as $fields) {
            fputcsv($fp, $fields);
        }
        fclose($fp);
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }        
        
        
        $this->render('index');
    }
    
    
    /**
     * Email all PNMs
     * 
     * @return void
     */
    public function actionEmailpnms()
    {
        $model=Pnm::model()->findAll();
        $arrEmails = array();
        foreach ($model as $pnm) {
            if (!empty($pnm->email)) {
                $arrEmails[] = $pnm->email;
            }
        }
                
        $this->render('emailpnms', array('arrEmails' => $arrEmails));
    }
    
    
    
    
    /**
     * Manages all PNMs
     * 
     * @return Void
     */
    public function actionAdmin()
    {
        $model=new Pnm('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Pnm'])) {
            $model->attributes=$_GET['Pnm'];
        }

        $this->render(
            'admin', array(
                'model'=>$model,
            )
        );
    }

    /**
     * Returns the PNM based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * 
     * @param integer $id the ID of the PNM to be loaded
     * 
     * @return PNM
     */
    public function loadModel($id)
    {
        $model=Pnm::model()->findByPk($id);
        if ($model===null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * 
     * @param CModel $model the model to be validated
     * 
     * @return void
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax']==='pnm-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
